package com.woniuxy.service.impl;

import com.woniuxy.entity.Food;
import com.woniuxy.mapper.FoodMapper;
import com.woniuxy.service.FoodService;
import lombok.AllArgsConstructor;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @BelongsProject: pigTrotterStore
 * @BelongsPackage: com.woniuxy.service
 * @Author: Quan
 * @Date: 2025/3/8 12:05
 */
@Service
public class FoodServiceImpl implements FoodService {
	@Resource
	private FoodMapper foodMapper;
	@Autowired
	private RedisTemplate<String, Object> redisTemplate;

	ReentrantLock lock = new ReentrantLock();

	@Override
	public List<Food> queryAll() {
		return foodMapper.queryAll();

	}

	@Override
	public Food queryFoodDetail(Integer id) {
		try {
			HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
			Food chareFood = (Food) hash.get("CHARE:FOODSERVICEIMPL:QUERYFOODDETAIL", id.toString());
			if (chareFood != null) {
				return chareFood;
			}
			if (lock.tryLock()) {
				Food food = foodMapper.queryFoodById(id);
				hash.put("CHARE:FOODSERVICEIMPL:QUERYFOODDETAIL", id.toString(), food);
				redisTemplate.expire("CHARE:FOODSERVICEIMPL:QUERYFOODDETAIL", 10+ new Random().nextInt(10), TimeUnit.DAYS);
				return food;
			} else {
				return null;
			}

		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (lock.isHeldByCurrentThread()) {
				lock.unlock();
			}
		}
	}

	@Override
	public List<Integer> queryIds() {
		return foodMapper.queryIds();
	}
}
